package cn.javaxc.mvcwork.controller;
import cn.javaxc.mvcwork.controller.*;
import cn.javaxc.mvcwork.modules.login.UserBean;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import cn.javaxc.mvcwork.util.common.MSecurityUtils;



public class Tracker {

  private final static int ADD = 1;
  private final static int REMOVE = -1;
  private int guestCount = 0;
  private int userCount = 0;
  private LinkedHashMap users = new LinkedHashMap();
  private ArrayList guests = new ArrayList();


  
  public Tracker() {
  }


  
  public int getGuestCount() {
    return guestCount;
  }


  
  public int getUserCount() {
    return userCount;
  }


  
  public void add(String sessionId, UserBean user) {
    adjustCount(sessionId, user, ADD);

  }


  
  public void remove(String sessionId) {
    adjustCount(sessionId, null, REMOVE);
  }


  
  private synchronized void adjustCount(String sessionId, UserBean user, int adjustment) {
    if (user != null) {
      if (user.getUserId()!=null) {
        TrackerElement element = new TrackerElement(user.getUserId());
        users.put(sessionId, element);
        userCount += adjustment;
        if (userCount < 0) {
          userCount = 0;
        }
      } else {
        guests.add(sessionId);
        guestCount += adjustment;
        if (guestCount < 0) {
          guestCount = 0;
        }
      }
    } else {
      if (users.containsKey(sessionId)) {
        userCount += adjustment;
        if (userCount < 0) {
          userCount = 0;
        }
        users.remove(sessionId);
      }
      if (guests.contains(sessionId)) {
        guestCount += adjustment;
        if (guestCount < 0) {
          guestCount = 0;
        }
        guests.remove(sessionId);
      }
    }
  }


  
  public int getTotalMembers(HttpServletRequest request) {
	return ((SystemStatus) request.getSession().getServletContext().getAttribute("SystemStatus")).getUserList().size();
  }

  public Collection getUserList() {
    return users.values();
  }
}
